package com.jpcc.vw.onlineRadio.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.CustomIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cns.android.account.CnsAccountInfo;
import com.cns.android.account.CnsAccountManager;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.cns.android.authentication.AppTokenInfo;
import com.cns.android.authentication.AppTokenManager;
import com.cns.android.helper.VehicleInfoHelper;
import com.cns.android.hmi.HMIManager;
import com.cns.android.media.MediaInfoManager;
import com.cns.android.onlineservice.OnlineServiceManager;
import com.cns.android.proximitysensor.ProximitySensorManager;
import com.cns.android.vehicle.VehicleManager;
import com.google.gson.Gson;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.base.BaseFragment;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.fragment.PlayerFragment;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.DownloadTrackAction;
import com.jpcc.vw.onlineRadio.model.action.RequestFocusRefreshAction;
import com.jpcc.vw.onlineRadio.model.action.ShowHideUnavailableAction;
import com.jpcc.vw.onlineRadio.model.action.StartPlayerAction;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.VIPInfoBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumMediaSessionManager;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.service.AudioFocusManager;
import com.jpcc.vw.onlineRadio.service.PlayAlbumRadioService;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.DeleteFileUtil;
import com.jpcc.vw.onlineRadio.utils.NetworkUtils;
import com.jpcc.vw.onlineRadio.utils.PermissionReq;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.SyncHisUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MainActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.layout_sources)
    RelativeLayout layout_sources;
    @BindView(R.id.layout_discover)
    RelativeLayout layout_discover;
    @BindView(R.id.layout_mylist)
    RelativeLayout layout_mylist;
    @BindView(R.id.layout_detail)
    RelativeLayout layout_detail;
    @BindView(R.id.layout_settings)
    RelativeLayout layout_settings;
    @BindView(R.id.frame_layout_content)
    FrameLayout frame_layout_content;
    @BindView(R.id.imv_top_search)
    ImageView imv_top_search;
    @BindView(R.id.imv_filter)
    ImageView imv_filter;
    @BindView(R.id.tv_sources)
    TextView tv_sources;
    @BindView(R.id.tv_discover)
    TextView tv_discover;
    @BindView(R.id.tv_mylist)
    TextView tv_mylist;
    @BindView(R.id.tv_detail)
    TextView tv_detail;
    @BindView(R.id.tv_setup)
    TextView tv_setup;
    @BindView(R.id.layout_status_error)
    RelativeLayout layout_status_error;
    @BindView(R.id.tv_hint)
    TextView tv_hint;


    @BindView(R.id.imv_left_radio)
    ImageView imv_left_radio;
    @BindView(R.id.imv_discovery_icon)
    ImageView imv_discovery_icon;
    @BindView(R.id.imv_playlist_icon)
    ImageView imv_playlist_icon;
    @BindView(R.id.imv_detail)
    ImageView imv_detail;
    @BindView(R.id.imv_setup)
    ImageView imv_setup;
    @BindView(R.id.imv_filter_sources)
    ImageView imv_filter_sources;


    @BindView(R.id.imv_left_radio_big)
    ImageView imv_left_radio_big;
    @BindView(R.id.imv_discovery_icon_big)
    ImageView imv_discovery_icon_big;
    @BindView(R.id.imv_playlist_icon_big)
    ImageView imv_playlist_icon_big;
    @BindView(R.id.imv_detail_big)
    ImageView imv_detail_big;
    @BindView(R.id.imv_setup_big)
    ImageView imv_setup_big;


    LinearLayout layout_source_right;


    RelativeLayout layout_bt_audio;

    RelativeLayout layout_am;

    RelativeLayout layout_fm;

    RelativeLayout layout_database;

    RelativeLayout layout_online_media;

    RelativeLayout layout_online_radio;

    private ImageView imv_radio;


    TextView tv_db;
    TextView tv_bt;
    TextView tv_online_music;
    TextView tv_online_radio;

    private BaseFragment sourcesFragment;
    private BaseFragment currentFragment;
    private BaseFragment discoverFragment;
    private BaseFragment myListFragment;
    private PlayerFragment playerFragment;
    private BaseFragment settingFragment;
    private FragmentManager mFragmentManager;
    private PlayServiceConnection serviceConnection;
    private int viewIndex = 3;
    private PlayAlbumRadioService playService;
    private BroadcastReceiver netwoorkReceiver;
    private boolean isServiceOn = false;
    private boolean isLogin = false;
    private int userType = -1;
    private boolean isNetworkAvaliable = true;
    private IRadio radioModel;
    private BroadcastReceiver networkChangeReceiver;
    //    private MosphereReceiver mosphereReceiver;
    private boolean registered = false;

    private View pop_source_view;
    private Dialog pop_source_dialog;
    private VehicleInfoHelper.ManagerServiceConnectionListener managerServiceConnectionListener;
    private BroadcastReceiver changeAccountReiver;
    private BroadcastReceiver tokenChangeReceiver;
    private BroadcastReceiver onlineServiceChangeReceiver;
    private boolean NetCauseReason = false;
    private BroadcastReceiver gestureDistanceReceiver;
    private BroadcastReceiver radioReceiver;
    private boolean isStatusRight = true;


    private BroadcastReceiver vipBroadcastReceiver;
    private BroadcastReceiver receiver;

    private Handler delayAccountHandler;
    private boolean onlineServiceStatus=true;


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public void initWindow() {
        Window window = getWindow();
        //隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏状态栏
        //定义全屏参数
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
//        window.setFlags(flag, flag);
        WindowManager.LayoutParams winParams = window.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        winParams.flags |= bits;
        window.setAttributes(winParams);
    }

    private void initUserInfo() {
        managerServiceConnectionListener = new VehicleInfoHelper.ManagerServiceConnectionListener() {
            @Override
            public void onManagerServiceConnect() {
                setupAccountOnlineServiceStatus();
                AppTokenInfo appTokenInfo = null;
                try {
                    appTokenInfo = AppTokenManager.getInstance(MainActivity.this).getAuthToken("mos_radio_service_v1");
                    PreferenceUtils.SaveTokenInfo(appTokenInfo);
                    Logger.i("appTokenInfo-->" + PreferenceUtils.GetTokenInfo());
                    CnsAccountInfo accountInfo = CnsAccountManager.getInstance(MainActivity.this).getAccountInfo();
                    PreferenceUtils.SaveAccountInfo(accountInfo);
                    Logger.i("accountInfo-->" + PreferenceUtils.GetAccountInfo());
                    String uuid = UUID.randomUUID().toString();
                    String deviceId = VehicleManager.getInstance(MainActivity.this).getHeadunitDeviceId();
                    PreferenceUtils.SaveDeviceId(deviceId);
                    Logger.i("deviceId-->" + PreferenceUtils.GetDeviceId());
                    String vinNumber = VehicleManager.getInstance(MainActivity.this).getVINNumber();
                    PreferenceUtils.SaveVinNum(vinNumber);
                    Logger.i("vinNumber-->" + PreferenceUtils.GetVinNum());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onManagerServiceDisconnection() {

            }
        };
        if (Constants.isRelease) {
            CnsAccountManager.getInstance(this).registerManagerServiceConnection(managerServiceConnectionListener);
        }
        if (Constants.isRelease) {
            IntentFilter filter = new IntentFilter(CustomIntent.ACTION_PROXIMITY_SENSOR_VALUE);
            gestureDistanceReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    float SensorDistance = ProximitySensorManager.getInstance(MainActivity.this).getProximitySensorValue();
                    //means close
                    if (SensorDistance == 0) {
//                        tv_sources.setVisibility(View.VISIBLE);
//                        tv_discover.setVisibility(View.VISIBLE);
//                        tv_mylist.setVisibility(View.VISIBLE);
//                        tv_detail.setVisibility(View.VISIBLE);
//                        tv_setup.setVisibility(View.VISIBLE);
//
//
//                        imv_left_radio.setImageResource(R.drawable.fm_06);
//                        imv_discovery_icon.setImageResource(R.drawable.search_06);
//                        imv_playlist_icon.setImageResource(R.drawable.browse_06);
//                        imv_detail.setImageResource(R.drawable.detail_06);
//                        imv_setup.setImageResource(R.drawable.setup_06);


                        imv_left_radio.setVisibility(View.GONE);
                        imv_discovery_icon.setVisibility(View.GONE);
                        imv_playlist_icon.setVisibility(View.GONE);
                        imv_detail.setVisibility(View.GONE);
                        imv_setup.setVisibility(View.GONE);

                        imv_left_radio_big.setVisibility(View.VISIBLE);
                        imv_discovery_icon_big.setVisibility(View.VISIBLE);
                        imv_playlist_icon_big.setVisibility(View.VISIBLE);
                        imv_detail_big.setVisibility(View.VISIBLE);
                        imv_setup_big.setVisibility(View.VISIBLE);


                        tv_sources.setVisibility(View.VISIBLE);
                        tv_discover.setVisibility(View.VISIBLE);
                        tv_mylist.setVisibility(View.VISIBLE);
                        tv_detail.setVisibility(View.VISIBLE);
                        tv_setup.setVisibility(View.VISIBLE);


                        if(playerFragment!=null){
                            playerFragment.setGesture(true);
                        }
                    }
                    //means far away
                    else {
//                        tv_sources.setVisibility(View.INVISIBLE);
//                        tv_discover.setVisibility(View.INVISIBLE);
//                        tv_mylist.setVisibility(View.INVISIBLE);
//                        tv_detail.setVisibility(View.INVISIBLE);
//                        tv_setup.setVisibility(View.INVISIBLE);
//
//
//                        imv_left_radio.setImageResource(R.drawable.fm_04);
//                        imv_discovery_icon.setImageResource(R.drawable.search_04);
//                        imv_playlist_icon.setImageResource(R.drawable.browse_04);
//                        imv_detail.setImageResource(R.drawable.detail_04);
//                        imv_setup.setImageResource(R.drawable.setup_04);


                        tv_sources.setVisibility(View.GONE);
                        tv_discover.setVisibility(View.GONE);
                        tv_mylist.setVisibility(View.GONE);
                        tv_detail.setVisibility(View.GONE);
                        tv_setup.setVisibility(View.GONE);


                        imv_left_radio_big.setVisibility(View.GONE);
                        imv_discovery_icon_big.setVisibility(View.GONE);
                        imv_playlist_icon_big.setVisibility(View.GONE);
                        imv_detail_big.setVisibility(View.GONE);
                        imv_setup_big.setVisibility(View.GONE);


                        imv_left_radio.setVisibility(View.VISIBLE);
                        imv_discovery_icon.setVisibility(View.VISIBLE);
                        imv_playlist_icon.setVisibility(View.VISIBLE);
                        imv_detail.setVisibility(View.VISIBLE);
                        imv_setup.setVisibility(View.VISIBLE);
                        if(playerFragment!=null){
                            playerFragment.setGesture(false);
                        }

                    }
                }
            };
            this.registerReceiver(gestureDistanceReceiver, filter);
        }
    }


    private void doSyncHistory() {
        SyncHisUtils.doSyncHistory();
    }


    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    private boolean isActivityTop(Class cls, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Logger.i("chang language-->" + newConfig.locale.getLanguage());
        String currentLanguage = newConfig.locale.getLanguage();
        if ("zh".equals(currentLanguage)) {
            tv_sources.setText("媒体源");
            tv_discover.setText("发现");
            tv_mylist.setText("播放列表");
            tv_detail.setText("详细信息");
            tv_setup.setText("设置");

            tv_db.setText("我的媒体");
            tv_bt.setText("蓝牙音频");
            tv_online_music.setText("在线媒体");
            tv_online_radio.setText("在线电台");


        } else {
            tv_sources.setText("Source");
            tv_discover.setText("Discover");
            tv_mylist.setText("My list");
            tv_detail.setText("Details");
            tv_setup.setText("Setup");


            tv_db.setText("My media");
            tv_bt.setText("BT audio");
            tv_online_music.setText("Online media");
            tv_online_radio.setText("Online radio");
        }
        mFragmentManager = getSupportFragmentManager();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (pop_source_dialog != null && pop_source_dialog.isShowing()) {
            pop_source_dialog.dismiss();
        }
    }

    @Override
    public void setupView() {
        mFragmentManager = getSupportFragmentManager();
        delayAccountHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);



                if(!onlineServiceStatus){
                    Logger.i("OnlineService Status-->"+onlineServiceStatus);
                    boolean androidSideFlag = false;
                    try {
                        int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                        if (side == 2) {
                            androidSideFlag = true;
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
                    boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
                    Logger.i("onlineRadio_front-->" + isRadioFront);
                    if (androidSideFlag && isRadioFront) {
                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                        setAlertIntent.putExtra("action", "ToLinuxOnlineService");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_78));
                        popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                        notificationManager.addPopup(0x00099, popup);
                    }
                    return;
                }

                if(!isNetworkAvaliable){
                    Logger.i("Network Status-->"+onlineServiceStatus);
                    boolean androidSideFlag = false;
                    try {
                        int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                        if (side == 2) {
                            androidSideFlag = true;
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
                    boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
                    Logger.i("onlineRadio_front-->" + isRadioFront);
                    if (androidSideFlag && isRadioFront) {
                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                        setAlertIntent.putExtra("action", "ToLinuxNetwork");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_125));
                        popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
//                        popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                        notificationManager.addPopup(0x00099, popup);
                    }
                    return;
                }









                if (userType == 3) {
                    boolean androidSideFlag = false;
                    try {
                        int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                        if (side == 2) {
                            androidSideFlag = true;
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
                    boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
                    Logger.i("onlineRadio_front-->" + isRadioFront);
                    if (androidSideFlag && isRadioFront) {
                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                        setAlertIntent.putExtra("action", "ToLinuxLogin");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_120));
                        popup.setActionOne(getResources().getString(R.string.string_122), pendingIntent);
                        popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                        notificationManager.addPopup(0x00099, popup);
                    }
                }
                //非A类账号中权限不足
                else if (userType == 2) {

                    boolean androidSideFlag = false;
                    try {
                        int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                        if (side == 2) {
                            androidSideFlag = true;
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
                    boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
                    Logger.i("onlineRadio_front-->" + isRadioFront);
                    if (androidSideFlag && isRadioFront) {
                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                        setAlertIntent.putExtra("action", "ToLinuxLogin");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_121));
                        popup.setActionOne(getResources().getString(R.string.string_123), pendingIntent);
                        popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                        notificationManager.addPopup(0x00099, popup);
                    }
                } else if ((userType == 0 || userType == 1)) {
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    notificationManager.cancel(0x00099);
                }
            }
        };
        if (playerFragment == null) {
            Logger.i("playerFragment == null");
            playerFragment = new PlayerFragment();
            mFragmentManager.beginTransaction().remove(playerFragment).commit();
            mFragmentManager.beginTransaction().add(R.id.frame_layout_content, playerFragment).commitAllowingStateLoss();
            AlbumRadioAudioPlayer.get().addOnPlayEventListener(playerFragment);
        }
        doSyncHistory();


        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if (intent.getAction().equals("com.jpcc.vw.onlineRadio.MainActivity")) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            if ("ToLinuxLogin".equals(bundle.getString("action"))) {
                                try {
                                    HMIManager.getInstance(MainActivity.this).switchToLinux(HMIManager.ENTRY_POINT_USER_MANAGEMENT_MAIN);
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                            //OnlineService开关
                            else if("ToLinuxOnlineService".equals(bundle.getString("action"))){

                            }
                            else if("ToLinuxNetwork".equals(bundle.getString("action"))){

                            }
                        }
                    }
                }
            }
        };
        IntentFilter toLinuxLoginFilter = new IntentFilter("com.jpcc.vw.onlineRadio.MainActivity");
        this.registerReceiver(receiver, toLinuxLoginFilter);
        initUserInfo();
        pop_source_view = View.inflate(MainActivity.this, R.layout.dialog_sources, null);
        initDialoigViews();
        initBindDialog();
//        else {
//            mFragmentManager.beginTransaction().hide(playerFragment).show(playerFragment).commitAllowingStateLoss();
//            AlbumRadioAudioPlayer.get().addOnPlayEventListener(playerFragment);
//        }
//        mFragmentManager.beginTransaction().add(R.id.frame_layout_content, playerFragment).commitAllowingStateLoss();
        bindService();
//        AlbumRadioAudioPlayer.get().addOnPlayEventListener(playerFragment);


        layout_detail.setSelected(true);
        EventBus.getDefault().register(this);

//        if (sourcesFragment == null) {
//            sourcesFragment = ViewFragmentUtils.createFragment(SourcesFragment.class, true);
//            currentFragment = sourcesFragment;
//            mFragmentManager.beginTransaction().add(R.id.frame_layout_content, currentFragment).commitAllowingStateLoss();
//        }
        if (false) {
            setupAccountOnlineServiceStatus();
        }
        radioModel = new RadioImpl();
//        mosphereReceiver = new MosphereReceiver();
//        IntentFilter mosphereFilter = new IntentFilter(CustomIntent.ACTION_ATMOSPHERE_LAMP_STATE);
//        this.registerReceiver(mosphereReceiver, mosphereFilter);


        layout_bt_audio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    HMIManager.getInstance(MainActivity.this).switchToLinux(HMIManager.ENTRY_POINT_MEDIA_BT_MAIN);
                    pop_source_dialog.dismiss();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        layout_am.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    HMIManager.getInstance(MainActivity.this).switchToLinux(HMIManager.ENTRY_POINT_TUNER_AM_MAIN);
                    pop_source_dialog.dismiss();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        layout_fm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    HMIManager.getInstance(MainActivity.this).switchToLinux(HMIManager.ENTRY_POINT_TUNER_FM_MAIN);
                    pop_source_dialog.dismiss();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        layout_database.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    HMIManager.getInstance(MainActivity.this).switchToLinux(HMIManager.ENTRY_POINT_MEDIA_JUKEBOX_MAIN);
                    pop_source_dialog.dismiss();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        layout_online_media.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    pop_source_dialog.dismiss();

                    Intent intentMedia = new Intent("com.cns.android.intent.action.PLAY_MEDIA");
                    MainActivity.this.sendBroadcast(intentMedia);


                    Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage("com.jpcc.vw.music");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "Media not installed", Toast.LENGTH_SHORT).show();
                }
            }
        });

        layout_online_radio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop_source_dialog.dismiss();
            }
        });
        IntentFilter filter = new IntentFilter(CustomIntent.ACTION_SVW_ACCOUNT_CHANGED);
        IntentFilter filterToken = new IntentFilter(CustomIntent.ACTION_SVW_TOKEN_CHANGED);
        IntentFilter filterOnlineService = new IntentFilter(CustomIntent.ACTION_ONLINESERVICE_STATE);
        IntentFilter filterVIPStatus = new IntentFilter("com.jpcc.vw.payment.constants.pay.result");
        this.changeAccountReiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("change vw account");
                CnsAccountManager.getInstance(MainActivity.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
                initUserInfo();
                if (!isActivityTop(MainActivity.class, MainActivity.this)) {
                    MusicApplication.GetInstance().finishOtherActivities();
                }
            }
        };
        this.tokenChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("change vw token");
                CnsAccountManager.getInstance(MainActivity.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
                initUserInfo();
                if (!isActivityTop(MainActivity.class, MainActivity.this)) {
                    MusicApplication.GetInstance().finishOtherActivities();
                }
            }
        };
        this.onlineServiceChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("change onlineService status");
                CnsAccountManager.getInstance(MainActivity.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
                initUserInfo();
                if (!isActivityTop(MainActivity.class, MainActivity.this)) {
                    MusicApplication.GetInstance().finishOtherActivities();
                }
            }
        };

        this.vipBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i("VIP Status changed!");
//                String vipBoughtStatus = intent.getStringExtra("payResult");
//                if ("101".equals(vipBoughtStatus)) {
//                    PreferenceUtils.SaveVIPStatus(true);
//                } else {
//                    PreferenceUtils.SaveVIPStatus(false);
//                }
                queryVipInfo();
            }
        };


        if (Constants.isRelease) {
            this.registerReceiver(changeAccountReiver, filter);
            this.registerReceiver(tokenChangeReceiver, filterToken);
            this.registerReceiver(onlineServiceChangeReceiver, filterOnlineService);
            this.registerReceiver(vipBroadcastReceiver, filterVIPStatus);
        }
        IntentFilter onlineRadioFilter=new IntentFilter("com.cns.android.intent.action.PLAY_RADIO");
        radioReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                AudioFocusManager audioFocusManager = AlbumRadioAudioPlayer.get().getAudioFocusManager();
                AlbumMediaSessionManager.get().updatePlaybackState();
                if (audioFocusManager != null) {
                    Logger.i("audioFocusManager is not null");
                    Logger.i("FLAG_FOCUS_ON_SELF-->" + Constants.FLAG_FOCUS_ON_SELF);
//                    try {
//                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }
                    RequestFocusRefreshAction action=new RequestFocusRefreshAction();
                    EventBus.getDefault().post(action);
                    if (!Constants.FLAG_FOCUS_ON_SELF) {
                        boolean gaiedAudioFocus=audioFocusManager.requestAudioFocus();
                        Logger.i("MainActivity-->send eventbus");
                        Logger.i("gaiedAudioFocus-->"+gaiedAudioFocus);
//                        RequestFocusRefreshAction action = new RequestFocusRefreshAction();
//                        EventBus.getDefault().post(action);
                        if(gaiedAudioFocus){
                            AlbumRadioAudioPlayer.get().startPlayer();
                            PreferenceUtils.SaveAudioFocusStatus(true);
                        }
                    } else {
                        AlbumRadioAudioPlayer.get().startPlayer();
                    }
                }
            }
        };
        this.registerReceiver(radioReceiver,onlineRadioFilter);
    }


    private void initDialoigViews() {
        layout_source_right = (LinearLayout) pop_source_view.findViewById(R.id.layout_source_right);
        layout_bt_audio = (RelativeLayout) pop_source_view.findViewById(R.id.layout_bt_audio);
        layout_am = (RelativeLayout) pop_source_view.findViewById(R.id.layout_am);
        layout_fm = (RelativeLayout) pop_source_view.findViewById(R.id.layout_fm);
        layout_database = (RelativeLayout) pop_source_view.findViewById(R.id.layout_database);
        layout_online_media = (RelativeLayout) pop_source_view.findViewById(R.id.layout_online_media);
        layout_online_radio = (RelativeLayout) pop_source_view.findViewById(R.id.layout_online_radio);

        tv_db = (TextView) pop_source_view.findViewById(R.id.tv_db);
        tv_bt = (TextView) pop_source_view.findViewById(R.id.tv_bt);
        tv_online_music = (TextView) pop_source_view.findViewById(R.id.tv_online_music);
        tv_online_radio = (TextView) pop_source_view.findViewById(R.id.tv_online_radio);

        imv_radio=(ImageView)pop_source_view.findViewById(R.id.imv_radio);

    }

    private void queryVipInfo() {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.QueryVIPInfo().subscribe(new CommonSubscriber<VIPInfoBean>() {
            @Override
            public void onSuccess(VIPInfoBean response) {
                if (response.getData() != null && response.getData().isVipFlag()) {
                    PreferenceUtils.SaveVIPStatus(true);
                } else {
                    PreferenceUtils.SaveVIPStatus(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
            }
        });
    }


    private void initBindDialog() {
        pop_source_dialog = new Dialog(this, R.style.AppBaseTheme);
        //获得dialog的window窗口
        Window window = pop_source_dialog.getWindow();
        //设置dialog在屏幕底部
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        window.getDecorView().setPadding(0, 28, 0, 0);
        //获得window窗口的属性
        //设置窗口宽度为充满全屏
        lp.width = 332;
        //设置窗口高度为包裹内容
//        lp.height = 620;
        lp.height = 620;
        //将设置好的属性set回去
        lp.x = 150;
        lp.y = 0;
//        lp.verticalMargin=0;
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        pop_source_dialog.setCancelable(true);
        pop_source_dialog.setCanceledOnTouchOutside(true);
        pop_source_dialog.setContentView(pop_source_view);
        pop_source_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                imv_filter_sources.setVisibility(View.GONE);
            }
        });
    }

    private void setLeftSlideEnable(boolean showErrorPage, String showContent) {
//        if (showErrorPage) {
//            layout_status_error.setVisibility(View.VISIBLE);
//            tv_hint.setText(showContent);
//        } else {
//            layout_status_error.setVisibility(View.GONE);
//        }
    }


    @Override
    public void setStatusBar() {
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void setupAccountOnlineServiceStatus() {
        registered = true;
        Logger.i("onlineServiceOn-->onManagerServiceConnect");
        try {
            if (CnsAccountManager.getInstance(MainActivity.this).getAccountInfo() == null) {
                Logger.i("onlineServiceOn-->account info is null");
            } else {
                Logger.i("onlineServiceOn-->" + 1);
                try {
                    CnsAccountInfo accountInfo = CnsAccountManager.getInstance(MainActivity.this).getAccountInfo();
                    Logger.i("account type-->" + accountInfo.getType());
                    userType = accountInfo.getType();
                    isLogin = !(accountInfo.getType() == 2 || accountInfo.getType() == 3);
                    AppTokenInfo tokenInfo = AppTokenManager.getInstance(MainActivity.this).getAuthToken("mos_radio_service_v1");
                    PreferenceUtils.SaveTokenInfo(tokenInfo);
                    Logger.i("token-->" + new Gson().toJson(tokenInfo));
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                if (Constants.isRelease) {
                    //首先判断OnlineService开关 如果是关的
                    onlineServiceStatus=OnlineServiceManager.getInstance(MainActivity.this).isOnlineServiceOn();
                    ConnectivityManager connectivityManager = (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                    boolean connected = connectivityManager.getNetworkStatus();
                    isNetworkAvaliable = connected;
                    Logger.i("NetworkInfo active = " + connected);
                    if(!onlineServiceStatus){
                        ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                        action.setHide(true);
                        action.setHintString(getResources().getString(R.string.string_78));
                        NetCauseReason = false;
                        isStatusRight = false;
                        playerFragment.setStatus(action);
                        setLeftSlideEnable(true, getResources().getString(R.string.string_78));
                        if (AlbumRadioAudioPlayer.get().isPlaying()) {
                            AlbumRadioAudioPlayer.get().pausePlayer(true);
                        }
                        playerFragment.setErrorStatus(true, getResources().getString(R.string.string_78));
                        AlbumRadioAudioPlayer.get().resetAlbumRadioPlayer();
                        Message accountMessage = Message.obtain();
                        delayAccountHandler.sendMessageDelayed(accountMessage, 600);
                        return;
                    }












                    if (false) {
                    } else {
                        isNetworkAvaliable = connected;
                        try {
                            isServiceOn = OnlineServiceManager.getInstance(MainActivity.this).isOnlineServiceOn();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        if (isNetworkAvaliable) {
                            if (!isLogin) {
//                                ShowHideUnavailableAction action = new ShowHideUnavailableAction();
//                                action.setHide(true);
//                                action.setHintString(getResources().getString(R.string.string_77));
//                                NetCauseReason = false;
//                                isStatusRight = false;
//                                playerFragment.setStatus(action);
//                                setLeftSlideEnable(true, getResources().getString(R.string.string_77));
//                                if (AlbumRadioAudioPlayer.get().isPlaying()) {
//                                    AlbumRadioAudioPlayer.get().pausePlayer(true);
//                                }
//                                playerFragment.setErrorStatus(true, getResources().getString(R.string.string_77));
//                                //A类账号 匿名账户 提示pop
//                                AlbumRadioAudioPlayer.get().resetAlbumRadioPlayer();
//
//                                Message accountMessage = Message.obtain();
//                                delayAccountHandler.sendMessageDelayed(accountMessage, 600);
                                //用户未登陆
                                if(userType==3){
                                    ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                    action.setHide(true);
                                    action.setHintString(getResources().getString(R.string.string_77));
                                    NetCauseReason = false;
                                    isStatusRight = false;
                                    playerFragment.setStatus(action);
                                    setLeftSlideEnable(true, getResources().getString(R.string.string_77));
                                    if (AlbumRadioAudioPlayer.get().isPlaying()) {
                                        AlbumRadioAudioPlayer.get().pausePlayer(true);
                                    }
                                    playerFragment.setErrorStatus(true, getResources().getString(R.string.string_77));
                                    //A类账号 匿名账户 提示pop
                                    AlbumRadioAudioPlayer.get().resetAlbumRadioPlayer();

                                    Message accountMessage = Message.obtain();
                                    delayAccountHandler.sendMessageDelayed(accountMessage, 600);
                                }
                                //用户权限不足
                                else if(userType==2){
                                    ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                    action.setHide(true);
                                    action.setHintString(getResources().getString(R.string.string_121));
                                    NetCauseReason = false;
                                    isStatusRight = false;
                                    playerFragment.setStatus(action);
                                    setLeftSlideEnable(true, getResources().getString(R.string.string_121));
                                    if (AlbumRadioAudioPlayer.get().isPlaying()) {
                                        AlbumRadioAudioPlayer.get().pausePlayer(true);
                                    }
                                    playerFragment.setErrorStatus(true, getResources().getString(R.string.string_121));
                                    //A类账号 匿名账户 提示pop
                                    AlbumRadioAudioPlayer.get().resetAlbumRadioPlayer();

                                    Message accountMessage = Message.obtain();
                                    delayAccountHandler.sendMessageDelayed(accountMessage, 600);
                                }
                            } else {
                                if (true) {//isNetworkAvaliable) {
                                    if (!isServiceOn) {
                                        ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                        action.setHide(true);
                                        action.setHintString(getResources().getString(R.string.string_78));
                                        NetCauseReason = false;
                                        isStatusRight = false;
                                        playerFragment.setStatus(action);
                                        setLeftSlideEnable(true, getResources().getString(R.string.string_78));
                                        if (AlbumRadioAudioPlayer.get().isPlaying()) {
                                            AlbumRadioAudioPlayer.get().pausePlayer(true);
                                        }
                                        playerFragment.setErrorStatus(true, getResources().getString(R.string.string_78));
                                    } else {
                                        ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                        action.setHide(false);
                                        NetCauseReason = false;
                                        isStatusRight = true;
//                                        EventBus.getDefault().postSticky(action);
                                        playerFragment.setStatus(action);
                                        if (playerFragment != null) {
                                            playerFragment.getVipInfo();
                                        }
                                        setLeftSlideEnable(false, "");
                                        playerFragment.setErrorStatus(false, "");
                                    }
                                } else {
                                    ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                    action.setHide(true);
                                    NetCauseReason = true;
                                    action.setHintString("No network is available");
//                                    EventBus.getDefault().postSticky(action);
                                    playerFragment.setStatus(action);
                                    setLeftSlideEnable(true, "No network is available");
                                }
                            }
                            Logger.i("isLogin-->" + isLogin);
                            Logger.i("isNetworkAvaliable-->" + isNetworkAvaliable);
                            Logger.i("isServiceOn-->" + isServiceOn);
                            Logger.i("setToken-->" + PreferenceUtils.GetTokenInfo());
                            if ((TextUtils.isEmpty(PreferenceUtils.GetTokenInfo())) || (TextUtils.isEmpty(new Gson().fromJson(PreferenceUtils.GetTokenInfo(), AppTokenInfo.class).getToken()))) {
                                ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                action.setHide(true);
                                action.setHintString(getResources().getString(R.string.string_77));
                                NetCauseReason = false;
                                isStatusRight = false;
//                                EventBus.getDefault().postSticky(action);
                                playerFragment.setStatus(action);
                                setLeftSlideEnable(true, getResources().getString(R.string.string_77));
                                playerFragment.setErrorStatus(true, getResources().getString(R.string.string_77));
                                if (AlbumRadioAudioPlayer.get().isPlaying()) {
//                                    AlbumRadioAudioPlayer.get().pausePlayer(true);
                                }
                            }
                        }
                        //网络不可用的状态下画面展示
                        else {
                            ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                            action.setHide(true);
                            action.setHintString(getResources().getString(R.string.string_124));
                            NetCauseReason = false;
                            isStatusRight = false;
                            playerFragment.setStatus(action);
                            playerFragment.setErrorStatus(true, getResources().getString(R.string.string_124));

                            Message accountMessage = Message.obtain();
                            delayAccountHandler.sendMessageDelayed(accountMessage, 600);




                        }
                    }
                } else {
                    Observable.create(new Observable.OnSubscribe<Boolean>() {
                        @Override
                        public void call(Subscriber<? super Boolean> subscriber) {
                            Socket s = null;
                            ConnectivityManager connectivityManager = (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                            boolean connected = (null != activeNetworkInfo) && activeNetworkInfo.isConnected();
//                        Log.d("lubin", "NetworkInfo active = " + connected);
                            Logger.i("NetworkInfo active = " + connected);
                            if (!connected) {
                                subscriber.onNext(false);
                                return;
                            }
                            boolean routeExists;
                            try {
                                if (s == null) {
                                    s = new Socket();
                                }
                                InetAddress host = InetAddress.getByName("8.8.8.8");//全球通用google：8.8.8.8
                                s.connect(new InetSocketAddress(host, 53), 5000);//google:53
                                routeExists = true;
                            } catch (IOException e) {
                                Log.d("lubin", "IOException = " + e.getMessage());
                                routeExists = false;
                            } finally {
                                try {
                                    s.close();
                                    s = null;
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            boolean bConnect = connected && routeExists;
                            Logger.i("NetworkInfo active = " + bConnect);
                            subscriber.onNext(connected && routeExists);
                        }
                    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<Boolean>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Boolean flag) {
                            Logger.i("onNext()-->" + flag);
//                        if (!flag) {
                            if (false) {
                                isNetworkAvaliable = false;
                                try {
                                    isServiceOn = OnlineServiceManager.getInstance(MainActivity.this).isOnlineServiceOn();
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                                if (!isLogin) {
                                    ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                    action.setHide(true);
                                    action.setHintString("VW Account not login");
//                                EventBus.getDefault().postSticky(action);
                                    NetCauseReason = false;
                                    playerFragment.setStatus(action);
                                    setLeftSlideEnable(true, "VW Account not login");
                                } else {
                                    if (isNetworkAvaliable) {
                                        if (!isServiceOn) {
                                            ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                            action.setHide(true);
                                            action.setHintString("Online Service is not available");
                                            NetCauseReason = false;
//                                        EventBus.getDefault().postSticky(action);
                                            playerFragment.setStatus(action);
                                            setLeftSlideEnable(true, "Online Service is not available");
                                        } else {
                                            ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                            action.setHide(false);
                                            NetCauseReason = false;
//                                        EventBus.getDefault().postSticky(action);
                                            playerFragment.setStatus(action);
                                            setLeftSlideEnable(false, "");
                                        }
                                    } else {
                                        ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                        action.setHide(true);
                                        action.setHintString("No network is available");
                                        NetCauseReason = true;
//                                    EventBus.getDefault().postSticky(action);
                                        playerFragment.setStatus(action);
                                        setLeftSlideEnable(true, "No network is available");
                                    }
                                }
                                Logger.i("isLogin-->" + isLogin);
                                Logger.i("isNetworkAvaliable-->" + isNetworkAvaliable);
                                Logger.i("isServiceOn-->" + isServiceOn);
                            } else {
                                isNetworkAvaliable = true;
                                try {
                                    isServiceOn = OnlineServiceManager.getInstance(MainActivity.this).isOnlineServiceOn();
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                                if (!isLogin) {
                                    ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                    action.setHide(true);
                                    action.setHintString("VW Account not login");
                                    NetCauseReason = false;
//                                EventBus.getDefault().postSticky(action);
                                    playerFragment.setStatus(action);
                                    setLeftSlideEnable(true, "VW Account not login");
                                } else {
                                    if (isNetworkAvaliable) {
                                        if (!isServiceOn) {
                                            ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                            action.setHide(true);
                                            action.setHintString("Online Service is not available");
                                            NetCauseReason = false;
//                                        EventBus.getDefault().postSticky(action);
                                            playerFragment.setStatus(action);
                                            setLeftSlideEnable(true, "Online Service is not available");
                                        } else {
                                            ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                            action.setHide(false);
                                            NetCauseReason = false;
//                                        EventBus.getDefault().postSticky(action);
                                            playerFragment.setStatus(action);
                                            setLeftSlideEnable(false, "");
                                        }
                                    } else {
                                        ShowHideUnavailableAction action = new ShowHideUnavailableAction();
                                        action.setHide(true);
                                        NetCauseReason = true;
                                        action.setHintString("No network is available");
//                                    EventBus.getDefault().postSticky(action);
                                        playerFragment.setStatus(action);
                                        setLeftSlideEnable(true, "No network is available");
                                    }
                                }
                                Logger.i("isLogin-->" + isLogin);
                                Logger.i("isNetworkAvaliable-->" + isNetworkAvaliable);
                                Logger.i("isServiceOn-->" + isServiceOn);
                            }
                        }
                    });
                }

            }
        } catch (RemoteException e) {
            e.printStackTrace();
            Logger.i(e.toString());
        }

    }


    private void bindService() {
        if (!isServiceWork(this, "com.jpcc.vw.onlineRadio.service.PlayAlbumRadioService")) {
            Logger.i("bindService()---》");
            PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
                @Override
                public void onGranted() {
//                    ToastUtils.show("获取了读写权限");
                    Intent intent = new Intent(MainActivity.this, PlayAlbumRadioService.class);
                    Constants.NeedInitDataFlag = true;
//                    startForegroundService(intent);
                    startService(intent);
                }

                @Override
                public void onDenied() {
//                    ToastUtils.show(R.string.string_37);
                    MainActivity.this.finish();
                }
            }).request();
        }
    }


    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    private boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playService = ((PlayAlbumRadioService.PlayBinder) service).getService();
            onServiceBound();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(getClass().getSimpleName(), "service disconnected");
        }
    }


    private Handler delayAndroidStatusHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            boolean androidSideFlag = false;
            try {
                int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                if (side == 2) {
                    androidSideFlag = true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
            boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
            Logger.i("onlineRadio_front-->" + isRadioFront);
            if (androidSideFlag&&isRadioFront) {
                if (Constants.isRelease) {

                    //以下是之前的实现
//                    if ((!AlbumRadioAudioPlayer.get().isPlaying()) && (!Constants.FLAG_PAUSE_MANUAL)) {
//                        AlbumRadioAudioPlayer.get().startPlayer();
//                    } else if (!Constants.FLAG_FOCUS_ON_SELF) {
//                        AudioFocusManager audioFocusManager = AlbumRadioAudioPlayer.get().getAudioFocusManager();
//                        if (audioFocusManager != null) {
//                            audioFocusManager.requestAudioFocus();
//                            Logger.i("MainActivity-->send eventbus");
//                            RequestFocusRefreshAction action = new RequestFocusRefreshAction();
//                            EventBus.getDefault().post(action);
//                        }
//                    }

                    //以下是最新的焦点策略实现
                    AudioFocusManager audioFocusManager = AlbumRadioAudioPlayer.get().getAudioFocusManager();
                    if (audioFocusManager != null) {
                        Logger.i("audioFocusManager is not null");
                        Logger.i("FLAG_FOCUS_ON_SELF-->" + Constants.FLAG_FOCUS_ON_SELF);
                        AlbumMediaSessionManager.get().updatePlaybackState();
                        if (!Constants.FLAG_FOCUS_ON_SELF) {
                            audioFocusManager.requestAudioFocus();
                            Logger.i("MainActivity-->send eventbus");
                            RequestFocusRefreshAction action = new RequestFocusRefreshAction();
                            EventBus.getDefault().post(action);
                        } else {
                            AlbumRadioAudioPlayer.get().startPlayer();
                        }
                    }

                }
            }
        }
    };

    private Handler delayDismissPopHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (pop_source_dialog != null && pop_source_dialog.isShowing()) {
                pop_source_dialog.dismiss();
            }
        }
    };

    @Override
    public void setupData() {
        super.setupData();
        if (Constants.isRelease) {
            try {
                Logger.i("register hmiCallback-->");
                HMIManager.getInstance(this).registerCurrentHMI(new HMIManager.CurrentHMISystemCallback() {
                    @Override
                    public void onCurrentHMISystemListener(int i) {
                        Logger.i("onlineRadio_onCurrentHMISystemListener----------------------------------------->>>>>" + i);
                        delayDismissPopHandler.sendEmptyMessageDelayed(0x12, 300);
                        if ((HMIManager.HMI_IN_ANDROID_FULL_SCREEN == i)) {
//                            Logger.i("onlineRadio_front-->" + ProcessInfoUtils.isForeground(MainActivity.this));
//                            if (ProcessInfoUtils.isForeground(MainActivity.this)&&(androidSideFlag)) {
//                                sif (Constants.isRelease) {
//                                    if ((!AlbumRadioAudioPlayer.get().isPlaying()) && (!Constants.FLAG_PAUSE_MANUAL)) {
//                                        AlbumRadioAudioPlayer.get().startPlayer();
//                                    } else if (!Constants.FLAG_FOCUS_ON_SELF) {
//                                        AudioFocusManager audioFocusManager = AlbumRadioAudioPlayer.get().getAudioFocusManager();
//                                        if (audioFocusManager != null) {
//                                            audioFocusManager.requestAudioFocus();
//                                        }
//                                    }
//                                }
//                            }

                            delayAndroidStatusHandler.sendEmptyMessageDelayed(0x90, 1800);
                            delayAccountHandler.sendEmptyMessageDelayed(0x11, 1800);
                            delayDismissPopHandler.sendEmptyMessageDelayed(0x12, 1800);
                        }
                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        networkChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Constants.isRelease) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                    boolean connected = connectivityManager.getNetworkStatus();
                    isNetworkAvaliable=connected;
                    Logger.i("MainActivity network-->" + connected);
                    if (!connected) {
                        if (ProcessInfoUtils.isForeground(MusicApplication.GetInstance())) {
                            ToastUtils.show(getResources().getString(R.string.string_106));
                        }
                    } else {
                        Logger.i("change network status");
                        if (PreferenceUtils.GetRadioPlayingStatus()) {
//                            AlbumRadioAudioPlayer.get().getTracks()
                        }
                        CnsAccountManager.getInstance(MainActivity.this).unregisterManagerServiceConnection(managerServiceConnectionListener);
                        initUserInfo();
                    }
                }
            }
        };
        IntentFilter networkFilter = new IntentFilter();
        networkFilter.addAction(CustomIntent.ACTION_NETWORK_CHANGED);
        if (Constants.isRelease) {
            this.registerReceiver(networkChangeReceiver, networkFilter);
        } else {
            networkFilter = new IntentFilter();
            networkFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            this.registerReceiver(networkChangeReceiver, networkFilter);
        }
//        Logger.i("isNetworkAvailable-->" + NetworkUtils.isNetworkAvailable(this));
        StartPlayerAction action = new StartPlayerAction();
        EventBus.getDefault().post(action);
        if (Constants.isRelease) {
            ConnectivityManager connectivityManager = (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean connected = connectivityManager.getNetworkStatus();
            if (!connected) {
                ToastUtils.show(getResources().getString(R.string.string_106));
            }
        }
    }


    @Override
    protected void onServiceBound() {
//        setupView();
//        updateWeather();
//        controlPanel = new ControlPanel(flPlayBar);
//        naviMenuExecutor = new NaviMenuExecutor(this);
//        AlbumRadioAudioPlayer.get().addOnPlayEventListener(playerFragment);
//        QuitTimer.get().setOnTimerListener(this);
//        parseIntent();
    }

//    private void getAlbumCollection(){
//        radioModel.GetAlbumRadioFavourite().subscribe(new CommonSubscriber<AlbumFavouriteBean>() {
//            @Override
//            public void onSuccess(AlbumFavouriteBean response) {
//
//            }
//
//            @Override
//            public void onFailure(BaseBean response) {
//
//            }
//        });
//    }

    private void clearSelectedStatus() {
//        layout_sources.setSelected(false);
//        layout_discover.setSelected(false);
//        layout_mylist.setSelected(false);
//        layout_settings.setSelected(false);
//        layout_detail.setSelected(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (Constants.isRelease) {
            if (gestureDistanceReceiver != null) {
                this.unregisterReceiver(gestureDistanceReceiver);
            }
        }
        if(radioReceiver!=null){
            this.unregisterReceiver(radioReceiver);
        }
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_filter.setColorFilter(Color.parseColor("#e6be00"));
                imv_radio.setColorFilter(Color.parseColor("#e6be00"));
                tv_online_radio.setTextColor(Color.parseColor("#e6be00"));
            } else {
                imv_filter.setColorFilter(Color.parseColor(color));
                imv_radio.setColorFilter(Color.parseColor(color));
                tv_online_radio.setTextColor(Color.parseColor(color));
            }
        } else {
            imv_filter.setColorFilter(Color.parseColor("#e6be00"));
            imv_radio.setColorFilter(Color.parseColor("#e6be00"));
            tv_online_radio.setTextColor(Color.parseColor("#e6be00"));
        }
        if (playerFragment != null) {
            playerFragment.setAtmosphere(rgbOn, color);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();


        if (pop_source_dialog != null && pop_source_dialog.isShowing()) {
            pop_source_dialog.dismiss();
        }
//        getPlayHistory();
//        imv_filter.setColorFilter(Color.parseColor("#10c4aa00"));
        if (Constants.isRelease) {
            try {
//                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isAtmosphereLampOn();
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                Logger.i("atmosphereStatus-->" + atmosphereStatus);
//                String color = AtmosphereLampManager.getInstance(this).getAtmosphereLampColor();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (!Constants.isRelease) {
            playerFragment.setAtmosphere(false, "#e6be00");
            imv_filter.setColorFilter(Color.parseColor("#e6be00"));
            imv_radio.setColorFilter(Color.parseColor("#e6be00"));
            tv_online_radio.setTextColor(Color.parseColor("#e6be00"));
        }


        if (Constants.isRelease) {


            boolean androidSideFlag2 = false;
            try {
                int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                if (side == 2) {
                    androidSideFlag2 = true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag2);
            boolean isRadioFront2 = ProcessInfoUtils.isForeground(MainActivity.this);
            Logger.i("onlineRadio_front-->" + isRadioFront2);

            if(!(isRadioFront2&&androidSideFlag2)){
                return;
            }


            if(!onlineServiceStatus){
                Logger.i("OnlineService Status-->"+onlineServiceStatus);
                boolean androidSideFlag = false;
                try {
                    int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                    if (side == 2) {
                        androidSideFlag = true;
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
                boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
                Logger.i("onlineRadio_front-->" + isRadioFront);
                if (androidSideFlag && isRadioFront) {
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                    setAlertIntent.putExtra("action", "ToLinuxOnlineService");
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_78));
                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                    notificationManager.addPopup(0x00099, popup);
                }
                return;
            }


            if(!isNetworkAvaliable){
                Logger.i("Network Status-->"+onlineServiceStatus);
                boolean androidSideFlag = false;
                try {
                    int side = (HMIManager.getInstance(MainActivity.this).getCurrentHMI());
                    if (side == 2) {
                        androidSideFlag = true;
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Logger.i("onlineRadio_getCurrentHMI-->" + androidSideFlag);
                boolean isRadioFront = ProcessInfoUtils.isForeground(MainActivity.this);
                Logger.i("onlineRadio_front-->" + isRadioFront);
                if (androidSideFlag && isRadioFront) {
                    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                    setAlertIntent.putExtra("action", "ToLinuxNetwork");
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_125));
                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                    notificationManager.addPopup(0x00099, popup);
                }
                return;
            }








            if (userType == 3) {

                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                setAlertIntent.putExtra("action", "ToLinuxLogin");
                PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_120));
                popup.setActionOne(getResources().getString(R.string.string_122), pendingIntent);
                popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                notificationManager.addPopup(0x00099, popup);
            }
            //非A类账号中权限不足
            else if (userType == 2) {

                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Intent setAlertIntent = new Intent("com.jpcc.vw.onlineRadio.MainActivity");
                setAlertIntent.putExtra("action", "ToLinuxLogin");
                PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_121));
                popup.setActionOne(getResources().getString(R.string.string_123), pendingIntent);
                popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                notificationManager.addPopup(0x00099, popup);
            } else if ((userType == 0 || userType == 1)) {
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(0x00099);
            }
        }


    }


    public void onEvent(DownloadTrackAction action) {
        if (TextUtils.isEmpty(action.getDir()) || TextUtils.isEmpty(action.getFileName())) {

        } else {
            PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
                @Override
                public void onGranted() {
//                    ToastUtils.show("获取了读写权限");
                }

                @Override
                public void onDenied() {
//                    ToastUtils.show(R.string.string_37);
                }
            }).request();
        }
    }


    private void getPlayHistory() {
    }


    class MosphereReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean rgbOn = intent.getBooleanExtra(CustomIntent.EXTRA_HMI_LAMP_ON, false);
            String rgbColor = intent.getStringExtra(CustomIntent.EXTRA_HMI_LAMP_COLOR);
            Logger.i("atmosphereRgbOn-->" + rgbOn);
            Logger.i("atmosphereRgbColor-->" + rgbColor);
            if (!TextUtils.isEmpty(rgbColor)) {
                if (rgbOn) {
                    layout_detail.setBackgroundColor(Color.parseColor(rgbColor));
                } else {
                    layout_detail.setBackgroundColor(Color.parseColor("#10e6be00"));
                }
            }
        }
    }


    @OnClick({R.id.layout_sources, R.id.layout_discover, R.id.layout_mylist, R.id.layout_detail, R.id.layout_settings, R.id.imv_top_search})
//    @OnClick(R.id.imv_top_search)
    public void doClicks(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.layout_sources:
//                if (isStatusRight){
                pop_source_dialog.show();
                String bgColor = "#e6be00";
                if (Constants.isRelease) {
                    try {
//                        boolean atmosphereStatus = AtmosphereLampManager.getInstance(MainActivity.this).isAtmosphereLampOn();
                        boolean atmosphereStatus = AtmosphereLampManager.getInstance(MainActivity.this).isHmiAtmosphereLampOn();
//                        String color = AtmosphereLampManager.getInstance(MainActivity.this).getAtmosphereLampColor();
                        String color = AtmosphereLampManager.getInstance(MainActivity.this).getHmiAtmosphereLampColor();
                        if (atmosphereStatus) {
                            if (!TextUtils.isEmpty(color)) {
                                bgColor = color;
                            }
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                imv_filter_sources.setVisibility(View.VISIBLE);
                imv_filter_sources.setColorFilter(Color.parseColor(bgColor));


//                }
                break;
            case R.id.layout_discover:
                if (isStatusRight) {
                    Intent intent1 = new Intent(this, BaseDiscoverActivity.class);
                    startActivity(intent1);
                }
                break;
            case R.id.layout_mylist:
                if (isStatusRight) {
                    Intent intent2 = new Intent(this, MyListActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.layout_detail:
                break;
            case R.id.layout_settings:
                if (isStatusRight) {
                    Intent intent3 = new Intent(this, SettingRadioActivity.class);
                    startActivity(intent3);
                }
                break;
            case R.id.imv_top_search:
                if (isStatusRight) {
                    Intent intent_search = new Intent(MainActivity.this, SearchActivity.class);
                    startActivity(intent_search);
                }
                break;
        }
    }
}
